package top.infopub.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;


/**
 * SFTP操作工具类 使用jsch.jar
 * @author Awoke
 * @version 2018年5月12日
 * @see SFTPUtils
 * @since
 */
public final class SFTPUtils {

    private static Logger log = LoggerFactory.getLogger(SFTPUtils.class);

    // 服务器连接ip
    private String host;

    // 用户名
    private String username;

    // 密码
    private String password;

    // 端口号
    private int port;

    private ChannelSftp sftp = null;

    private Session sshSession = null;

    public SFTPUtils() {}

    public SFTPUtils(FtpUser config) {
        this.host = config.getIp();
        this.username = config.getUserName();
        this.password = config.getPassword();
        this.port = Integer.valueOf(config.getPort());
    }

    /**
     * 上传单个文件
     * @param localFile：本地需要上传的文件
     * @param remotePath：远程保存目录
     * @param remoteFileName：保存文件名
     * @return
     */
    public boolean uploadFile(File localFile, String remotePath, String remoteFileName) {
        String localPath = FilenameUtils.getFullPath((localFile.getPath()));
        String localFileName = FilenameUtils.getName(localFile.getPath());
        return uploadFile(localPath, localFileName, remotePath, remoteFileName);
    }

    /**
     * 上传单个文件
     * @param localPath：本地上传目录
     * @param localFileName：上传的文件名
     * @param remotePath：远程保存目录
     * @param remoteFileName：保存文件名
     * @return
     */
    public boolean uploadFile(String localPath, String localFileName, String remotePath,
                              String remoteFileName) {
        if (!remotePath.endsWith("/")) {
            remotePath = remotePath + "/";
        }
        if (!localPath.endsWith("/")) {
            localPath = localPath + "/";
        }
        FileInputStream in = null;
        try {
            connect();
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            sftp.put(in, remoteFileName);
            log.info(
                "SFTPUtils#uploadFile successfully~ localPath={}, localFileName={}, remotePath={}, remoteFileName={} ",
                new Object[] {localPath, localFileName, remotePath, remoteFileName});
            return true;
        }
        catch (Exception e) {
            log.error("uploadFile error", e);
            return false;
        }
        finally {
            IOUtils.closeQuietly(in);
            disconnect();
        }
    }

    /**
     * 下载单个文件<本地目录如果不存在会先创建>
     * @param remotPath：远程下载目录
     * @param remoteFileName：下载文件名
     * @param localPath：本地保存目录
     * @param localFileName：保存文件名
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFileName, String localPath,
                                String localFileName) {
        if (!remotePath.endsWith("/")) {
            remotePath = remotePath + "/";
        }
        if (!localPath.endsWith("/")) {
            localPath = localPath + "/";
        }
        FileOutputStream fieloutput = null;
        try {
            connect();
            sftp.cd(remotePath);
            File file = new File(localPath + localFileName);
            mkdirs(localPath + localFileName);
            fieloutput = new FileOutputStream(file);
            // 注意：sftp.cd()到当前文件夹后，查询对应的文件是否存在，不需要再带路径 
            sftp.get(remoteFileName, fieloutput);
            return true;
        }
        catch (Exception e) {
            log.error("downloadFile error", e);
            return false;
        }
        finally {
            IOUtils.closeQuietly(fieloutput);
            disconnect();
        }
    }

    /**
     * 批量下载文件<本地目录如果不存在会先创建>
     * @param remotPath：远程下载目录
     * @param localPath：本地保存目录
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath) {
        if (!remotePath.endsWith("/")) {
            remotePath = remotePath + "/";
        }
        if (!localPath.endsWith("/")) {
            localPath = localPath + "/";
        }
        List<String> filenames = new ArrayList<String>();
        FileOutputStream fieloutput = null;
        try {
            connect();
            Vector<?> v = sftp.ls(remotePath);
            // 切换到目录下
            sftp.cd(remotePath);
            if (v.size() > 0) {
                Iterator<?> it = v.iterator();
                while (it.hasNext()) {
                    LsEntry entry = (LsEntry)it.next();
                    String filename = entry.getFilename();
                    SftpATTRS attrs = entry.getAttrs();
                    if (!attrs.isDir()) {
                        String localFileName = localPath + filename;
                        // 创建
                        mkdirs(localFileName);
                        fieloutput = new FileOutputStream(new File(localFileName));
                        // 注意：sftp.cd()到当前文件夹后，查询对应的文件是否存在，不需要再带路径 
                        sftp.get(filename, fieloutput);
                        filenames.add(localFileName);
                    }
                }
            }
            log.info("download file success:remotePath=" + remotePath + "and localPath="
                     + localPath + ",file size is" + v.size());
            return filenames;
        }
        catch (Exception e) {
            log.error("downloadFile error", e);
            return Lists.newArrayList();
        }
        finally {
            IOUtils.closeQuietly(fieloutput);
            disconnect();
        }
    }

    /**
     * 创建目录 并且cd当当前的目录下
     * @param createpath
     * @return
     */
    private boolean createDir(String createpath)
        throws Exception {
        if (isDirExist(createpath)) {
            sftp.cd(createpath);
            return true;
        }
        String pathArry[] = createpath.split("/");
        StringBuilder filePath = new StringBuilder("");
        for (String path : pathArry) {
            if (path.equals("")) {
                continue;
            }
            filePath.append(path + "/");
            if (isDirExist(filePath.toString())) {
                sftp.cd(filePath.toString());
            }
            else {
                // 建立目录
                sftp.mkdir(path);
                // 进入并设置为当前目录
                sftp.cd(path);
            }
        }
        return true;
    }

    /**
     * 判断目录是否存在
     * @param directory
     * @return
     */
    private boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        }
        catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * 如果本地目录不存在则创建
     * @param path
     */
    private void mkdirs(String path) {
        File f = new File(path);
        String fs = f.getParent();
        f = new File(fs);
        if (!f.exists()) {
            f.mkdirs();
        }
    }

    /**
     * 通过SFTP连接服务器
     */
    private void connect()
        throws Exception {
        JSch jsch = new JSch();
        jsch.getSession(username, host, port);
        sshSession = jsch.getSession(username, host, port);
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp)channel;
    }

    /**
     * 关闭连接
     */
    private void disconnect() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
            }
        }
    }

    /**
     * test
     * @param args
     * @throws Exception 
     * @see
     */
    public static void main(String[] args) {
        FtpUser user = new FtpUser("114.251.243.97", "20000", "JSJYTEST", "91481h5f");
        SFTPUtils t = new SFTPUtils(user);
        try {
            //t.uploadFile("20180512", "ss.txt", "D:/pdf", "ss.txt");
            //t.downloadFile("20180512", "JK.txt", "D:/pdf/dd/ss/汉字", "sss.txt");
            //t.batchDownLoadFile("20180512", "D:/pdf/CHK/20180512");
            //            t.connect();
            //            t.sftp.mkdir("20180512");
            //            t.sftp.cd("20180512/");
            //            t.sftp.mkdir("test");
            //            t.disconnect();
            //File localFile = new File("D:/pdf/ss/sdddd/ss.txt");
            /*File localFile = new File("D:/pdf/ss/sdddd/ss.txt.OK");
            String localPath = FilenameUtils.getFullPath((localFile.getPath()));
            String localFileName = FilenameUtils.getName(localFile.getPath());
            System.out.println(localFile.getPath());
            System.out.println(localPath);
            System.out.println(localFileName);*/
            t.uploadFile(
                new File(
                    "D:/opt/ossDownFile/preLoan/317C40847AD64D1C87C64D30A1449253/JSJY01_JSJY012019110100002.zip"),
                "/JSJY01/receive/40", "JSJY01_JSJY012019110100002.zip");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {}
    }

}